package org.jeecg.expression.func.type;

import java.math.BigDecimal;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDecimal;
import com.googlecode.aviator.runtime.type.AviatorObject;

@Component
public class RecursionFunc extends AbstractSpringAviatorFunction {

	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject orginValue, AviatorObject values,
			AviatorObject operation, AviatorObject compareValue) {
		BigDecimal orgin = new BigDecimal(orginValue.numberValue(env).doubleValue());
		String[] o = FunctionUtils.getStringValue(values,env).split(",");
		String op = operation.stringValue(env);
		BigDecimal compare = new BigDecimal(compareValue.numberValue(env).doubleValue());
		//BigDecimal result = BigDecimal.ZERO;
		int availMonths = 0;
		for (String valueString : o) {
			BigDecimal value = BigDecimal.ZERO;
			if(valueString != "" && valueString != null){
				value = new BigDecimal(valueString);
			}
			
			orgin = orgin.subtract(value);
			boolean b = false;
			switch (op) {
			case "eq":
				b = orgin.compareTo(compare)==0;
				break;
			case "gt":
				b = orgin.compareTo(compare)==1;
				break;
			case "ge":
				b = orgin.compareTo(compare)>=0;
				break;
			case "lt":
				b = orgin.compareTo(compare)==-1;
				break;
			case "le":
				b = orgin.compareTo(compare)<=0;
				break;
			default:
				break;
			}
			if(b){
				break;
			}else{
				availMonths++;
			}
		}
		return new AviatorDecimal(availMonths);
	}

	@Override
	public String getName() {
		return "recur";
	}

	@Override
	public boolean disabled() {
		return false;
	}

	/*public static void main(String[] args) {
		String s = "aa,11,'bb',[[2,2],2,3]";
		String[] str = new String[3];
		str[0] = "111";
		str[1] = "222";
		str[2] = "333";
		String[] ss = s.split(",(?![^\\[]*?\\])");
		for (String t : ss) {
			System.out.println(t);
		}
		// 注册函数
		Map<String, Object> env = new HashMap<>();
		env.put("str", str);
		AviatorEvaluator.addFunction(new RecursionFunc());
		System.out.println(AviatorEvaluator.execute("recur(str)", env)); // 3.0
	}*/

	@Override
	public String getText() {
		return "recur(p0,p1,p2,p3)";
	}
}

//recur(quantity,[M_0_xuqiu,M_1_xuqiu,M_2_xuqiu,M_3_xuqiu,M_4_xuqiu,M_5_xuqiu,M_6_xuqiu,M_7_xuqiu,M_8_xuqiu,M_9_xuqiu,M_10_xuqiu,M_11_xuqiu],'lt',0)